package com.study.csv;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

/**
 * <p>添加类描述</p>
 *
 * @author chentao
 * @version v 0.1 2024/6/17 16:50
 */
public class Csv3 {
    public static void main(String[] args) throws IOException {
        String v1 =null;
        String v2 = "name2:v2";
        File file = new File("C:\\test\\test33.csv");
        FileOutputStream out = new FileOutputStream(file);

        // Determine if v1 and v2 are present
        boolean hasV1 = v1 != null && !v1.isEmpty();
        boolean hasV2 = v2 != null && !v2.isEmpty();

        // Adjust header row
        StringBuilder header = new StringBuilder("\t姓名,\t年级");
        if (hasV1) {
            header.append(",\t").append(v1.split(":")[1]);
        }
        if (hasV2) {
            header.append(",\t").append(v2.split(":")[1]);
        }
        header.append("\r\n");

        // Write header to file
        out.write(header.toString().getBytes("GBK"));

        // Prepare data rows
        ArrayList<Person> peoples = new ArrayList<>();
        Person person = new Person();
        person.setName("1");
        person.setAge("1");
        person.setName1("setName1");
        person.setName2("setName2");
        peoples.add(person);

        for (Person people : peoples) {
            StringBuilder row = new StringBuilder();
            row.append("\t").append(people.getName()).append(",\t").append(people.getAge());
            if (hasV1) {
                row.append(",\t").append(people.getName1());
            }
            if (hasV2) {
                row.append(",\t").append(people.getName2());
            }
            row.append("\r\n");
            out.write(row.toString().getBytes("GBK"));
        }

        out.close();
    }
}

